package gspushmq.v1.produce.job.hq;

import java.util.Date;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.java_websocket.WebSocket;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

import ggframework.util.GGConfigurer;
import ggframework.util.GGLogger;
import gogoal.api.GoGoalAPI;
import gspushmq.model.ConsumerWays;
import gspushmq.model.DataMessage;
import gspushmq.model.LinkEnum;
import gspushmq.model.Message;
import gspushmq.model.MessageType;
import gspushmq.model.PrefixEnum;
import gspushmq.model.SkipConstant;
import gspushmq.util.DateUtil;
import gspushmq.util.SysUtil;

/**
 * @Description 360周报服务
 * @Author 成尚佳
 * @Date 2018/12/13 17:02
 * @Version 1.0
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2015 SunTime Co'Ltd Inc. All rights reserved.
 **/
public class WReportService {


    /**
     * @param
     * @description 360周报推送，订阅即推送
     * @version 1.0
     * @author chengsja
     * @date 2018/12/13 17:51
     */
    public static void dealWReport360(Message message, WebSocket ws) {

        Integer productLine = Integer.valueOf(message.getProduct_line());
        Long accountId = Long.valueOf(message.getAccount_id());
        Set<DataMessage> dataMessageSet = SysUtil.listNoExpiredMessages(message);
        Set<String> pdm = SysUtil.getUUIDs(dataMessageSet);
        Set<DataMessage> waitMessageSet = SysUtil.removeConsumeredMUUID(dataMessageSet,message);
        //生产360消息
        if (pdm == null || pdm.size() == 0) {
            //远程调用
            JSONObject preMessage = getUser360WRport(accountId, 2);
            String content = create360Message(preMessage);
            String title = create360Title(preMessage);
            MessageType messageType = new MessageType();
            messageType.setMq_type(PrefixEnum.WREPORT360.getMqType());
            messageType.setMq_sub_type(PrefixEnum.WREPORT360.getMqSubType());
            if (StringUtils.isNotBlank(content) && StringUtils.isNotBlank(title)) {
                DataMessage dm = new DataMessage();
                dm.setMqType(PrefixEnum.WREPORT360.getMqType());
                dm.setMqSubType(PrefixEnum.WREPORT360.getMqSubType());
                dm.setCrowdType(ConsumerWays.ALIAS.getWay());
                dm.setCrowdValue(String.valueOf(accountId));
                dm.setExpireDate(getExpireDate(preMessage));
                dm.setStartDate(new Date());
                dm.setTitle(title);
                dm.setContent(content);
                //2弹窗
                dm.setLinkType(LinkEnum.WINDOW.getLinkType());
                //弹窗url
                dm.setModule(SkipConstant.WREPORT_360_LINK_URL);
                //弹窗url
                dm.setLinkUrl(SkipConstant.WREPORT_360_LINK_URL);
                dm.setProductLine(productLine);
                //入库
                SysUtil.sendToMongo(dm);
                //日志
                SysUtil.logPattern(WReportService.class, dm);
                //消费
                SysUtil.sendWebSocket(message, ws, dm);
            }
        }else {
            //登录消费
            SysUtil.loginConsumer(message,ws,waitMessageSet);
        }

    }

    /**
     * 根据消息类型，产品线集合投递相应产品线的消息
     *
     * @param messageType  消息类型
     * @param dataMessage  消息体
     * @param productLines 产品线集合
     *                     Created by chengsj on 2018/11/27
     */
    public static void addDataMessageInProductLine(DataMessage dataMessage, MessageType messageType, Set<Integer> productLines) {
        if (dataMessage == null || productLines == null || productLines.size() == 0 || messageType == null) {
            return;
        }
        for (Integer i : productLines) {
            DataMessage dm = new DataMessage();
            dm.setUuid(dataMessage.getUuid());
            dm.setProductLine(i);
            dm.setMqType(dataMessage.getMqType());
            dm.setMqSubType(dataMessage.getMqSubType());
            dm.setCrowdType(dataMessage.getCrowdType());
            dm.setCrowdValue(dataMessage.getCrowdValue());
            dm.setExpireDate(dataMessage.getExpireDate());
            dm.setTitle(dataMessage.getTitle());
            dm.setContent(dataMessage.getContent());
            dm.setLinkType(dataMessage.getLinkType());
            dm.setModule(dataMessage.getModule());
            dm.setLinkUrl(dataMessage.getLinkUrl());
            //...
            //入库
            SysUtil.sendToMongo(dm);
            //日志
            SysUtil.logPattern(WReportService.class, dm);
        }
    }


    /**
     * 获取过期时间,周报截止时间的下周6上午8:40
     * <p>
     * Created by chengsj on 2018/11/22
     */
    private static Date getExpireDate(JSONObject preMessage) {
        if (preMessage == null || preMessage.size() == 0) {
            return null;
        }
        JSONObject actMessage = preMessage.getJSONObject("data");
        if (actMessage == null || actMessage.size() == 0 || "0".equals(actMessage.getString("mystock"))) {
            return null;
        }
        Date lastDate = actMessage.getDate("end_date");
        //周6:8:40
        return DateUtil.getNextWeekDate(lastDate, 6, 8, 40, 0);
    }


    /**
     * 组装360周报提示语的格式
     * Created by chengsj on 2018/10/24
     */
    private static String create360Message(JSONObject preMessage) {
        if (preMessage == null || preMessage.size() == 0) {
            return null;
        }
        JSONObject actMessage = preMessage.getJSONObject("data");
        if (actMessage == null || actMessage.size() == 0 || "0".equals(actMessage.getString("mystock"))) {
            return null;
        }
        String endDate = DateUtil.dateToString(actMessage.getDate("end_date"), "yyyy-MM-dd");
        StringBuffer content = new StringBuffer("截止")
                .append(endDate)
                .append(",您的自选股股票池共有").append(actMessage.getString("top_300")).append("只股票入选评分top300股票池")
                .append(",\n出现超预期或可能超预期信号的有").append(actMessage.getString("performance_signal")).append("只")
                .append(",\n发生重大事件的信号的有").append(actMessage.getString("major_event")).append("只")
                .append(",\n市场和资金重点关注有").append(actMessage.getString("market_focus")).append("只");

        return content.toString();
    }

    /**
     * 组装360周报标题
     * Created by chengsj on 2018/11/28
     */
    private static String create360Title(JSONObject preMessage) {
        if (preMessage == null || preMessage.size() == 0) {
            return null;
        }
        JSONObject actMessage = preMessage.getJSONObject("data");
        if (actMessage == null || actMessage.size() == 0 || "0".equals(actMessage.getString("mystock"))) {
            return null;
        }
        String startDate = DateUtil.dateToString(actMessage.getDate("start_date"), "yyyy-MM-dd");
        String endDate = DateUtil.dateToString(actMessage.getDate("end_date"), "yyyy-MM-dd");
        StringBuffer titleBuffer = new StringBuffer();
        titleBuffer.append("自选股360周报(").append(startDate).append("至").append(endDate).append(")");
        return titleBuffer.toString();
    }

    /**
     * 远程调用，获取该用户的360周报综合分析数据
     * 远程接口：v1/mystock360/get_comprehensive_analysis? group_id = 1 & account_id = uid & con_date = new date()
     *
     * @param uid     用户id
     * @param redoMax 远程失败重启次数
     *                Created by chengsj on 2018/10/24
     */
    private static JSONObject getUser360WRport(Long uid, Integer redoMax) {
        String api = "v1/mystock360/get_comprehensive_analysis";
        String resp = null;
        Map<String, String> params = Maps.newHashMap();
        params.put("account_id", String.valueOf(uid));
        params.put("con_date", new Date().toString());
        try {
            resp = GoGoalAPI.get(GGConfigurer.get("api.domain"), GGConfigurer.get("api.appKey"), GGConfigurer.get("api.appSecret"), api, params);
        } catch (Exception e) {
            GGLogger.error(WReportService.class, "远程调用用户360周报数据出错，用户id：" + uid);
        }
        JSONObject preMessage = JSONObject.parseObject(resp);
        if (preMessage != null && preMessage.size() > 0) {
            return preMessage;
        } else {
            if (--redoMax >= 0) {
                return getUser360WRport(uid, redoMax);
            }
        }
        return preMessage;
    }

}
